import {
  ViewController,
  IGridViewEvent,
  IGridViewState,
  MDViewEngine,
  IGridController,
  SysUIActionTag,
  IChartController
} from '@ibiz-template/runtime'
import { IAppDEGridView } from '@ibiz/model-core'

/**
 * 扩展表格视图引擎
 *
 * @export
 * @class ExtendGridViewEngin
 * @extends {GridViewEngine}
 */
export class ExtendGridViewEngin extends MDViewEngine {
  /**
   * 图表
   *
   * @readonly
   * @type {IChartController}
   * @memberof ExtendGridViewEngin
   */
  get chart(): IChartController {
    return this.view.getController('chart') as IChartController
  }

  /**
   * 表格
   *
   * @readonly
   * @type {IGridController}
   * @memberof ExtendGridViewEngin
   */
  get grid(): IGridController {
    return this.view.getController('grid') as IGridController
  }

  /**
   * 视图
   *
   * @protected
   * @type {ViewController<
   *     IAppDEGridView,
   *     IGridViewState,
   *     IGridViewEvent
   *   >}
   * @memberof ExtendGridViewEngin
   */
  protected declare view: ViewController<IAppDEGridView, IGridViewState, IGridViewEvent>

  /**
   * 执行能力
   *
   * @param {string} key
   * @param {*} args
   * @return {*}  {(Promise<IData | null | undefined>)}
   * @memberof ExtendGridViewEngin
   */
  async call(key: string, args: any): Promise<IData | null | undefined> {
    if (key === SysUIActionTag.NEW_ROW) {
      this.grid.newRow()
      return null
    }
    if (key === SysUIActionTag.TOGGLE_ROW_EDIT) {
      this.grid.toggleRowEdit()
      return null
    }
    if (key === SysUIActionTag.SAVE_ROW) {
      this.grid.save(args.data[0])
      return null
    }
    if (key === SysUIActionTag.SAVE) {
      this.grid.saveAll()
      return null
    }

    return super.call(key, args)
  }

  /**
   * 视图mounted生命周期执行逻辑
   *
   * @return {*}  {Promise<void>}
   * @memberof ExtendGridViewEngin
   */
  async onCreated(): Promise<void> {
    super.onCreated()
    const { model } = this.view
    if (!this.view.slotProps.grid) {
      this.view.slotProps.grid = {}
    }
    this.view.slotProps.grid.mdctrlActiveMode = model.gridRowActiveMode!
    this.view.slotProps.grid.rowEditOpen = model.rowEditDefault!
  }

  /**
   * 视图mounted生命周期执行逻辑
   *
   * @return {*}  {Promise<void>}
   * @memberof ExtendGridViewEngin
   */
  async onMounted(): Promise<void> {
    await super.onMounted()
    setTimeout(() => {
      this.chart.evt.on('onBeforeLoad', () => {
        this.chart.state.searchParams = this.getSearchParams()
      })
    }, 300)
  }

  /**
   * 视图重新加载(重写)
   *
   * @protected
   * @return {*}  {Promise<void>}
   * @memberof ExtendGridViewEngin
   */
  protected async reLoad(): Promise<void> {
    if (this.chart) {
      await this.chart.load({ isInitialLoad: true })
    }
    await this.xdataControl.load({ isInitialLoad: true })
  }
}
